package com.xingkeduo.pojo.json;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xingkeduo.pojo.query.VendorQuery;
import com.xingkeduo.pojo.table.VendorTable;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.domain.Page;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.CommonUtil;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.List;

public class VendorJson extends BaseJson {

	//查询
	public static VendorQuery createQueryForVendor(String json) throws Throwable {
		VendorQuery query = new VendorQuery();
		JsonNode root = validJson(json);
		if (root == null)
			return query;
		query.setId(validId(root, YesNoEnum.YES));
		return query;
	}

	//修改
	public static VendorTable createTableForModifyVendor(String urlParam, VendorTable vendorTable) throws Throwable {
		JsonNode root = validJson(urlParam);
		if (root == null)
			throw new InputParamException(InputParamException.Type.INVALID, "参数");
		vendorTable.setId(validId(root, YesNoEnum.YES));

		return vendorTable;
	}

	public static ObjectNode toJson(VendorTable vendorTable) {
		ObjectNode root = MAPPER.createObjectNode();

		if (vendorTable != null)
		{
			root.put("id", vendorTable.getId());
			root.put("code", vendorTable.getCode());
			root.put("name", vendorTable.getName());
			root.put("manager", vendorTable.getManager());
			root.put("phone", vendorTable.getPhone());
			root.put("status", vendorTable.getStatus());
			//处理时间
			String createdTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(vendorTable.getCreatedTime());
//			String createdTime = DateFormat.getDateTimeInstance().format(vendorTable.getCreatedTime());//可以精确到时分秒
			root.put("createtime", createdTime);
		}

		return root;
	}

	public static ArrayNode toJson(List<VendorTable> vendorTableList) throws Throwable {
		ArrayNode root = MAPPER.createArrayNode();

		if(!CommonUtil.isEmpty(vendorTableList)){
			for (Iterator<VendorTable> iterator = vendorTableList.iterator(); iterator.hasNext();) {
				root.add(toJson(iterator.next()));
			}
		}

		return root;
	}

	public static ObjectNode toJsonPage(Page<VendorTable> page) throws Throwable {
		ObjectNode root = MAPPER.createObjectNode();
		if (page != null)
		{
			root.put("pageNo", page.getPageNo());
			root.put("pageSize", page.getPageSize());
			root.put("pageTotal", page.getPageTotal());
			root.put("recordTotal", page.getRecordTotal());
			root.put("dtoLists", toJson(page.getDtoList()));
		}
		return root;
	}
}
